﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cnm.Core;
using Cnm.Core.Caching;
using Cnm.Models;
using Cnm.Models.ViewModels;
using Cnm.Mvc.Web.Ultilities;
using Cnm.Servicers.Cacher;
using Cnm.Servicers.Localization;
using Cnm.Servicers.Seo;

namespace Cnm.Mvc.Web.Controllers
{
    public class CatalogController : Controller
    {
        private CnmDemoEntities dbContext = new CnmDemoEntities();

        private ICacher _cacher;
        private ICacheManager _cacheManager;
        private IWorkContext _workContext;
        public const string PRODUCT_BREADCRUMB_MODEL_KEY = "Nop.pres.category.breadcrumb-{0}-{1}";
        public CatalogController(ICacher cacher, ICacheManager cacheManager, IWorkContext workContext)
        {
            this._cacher = cacher;
            _cacheManager = cacheManager;
            _workContext = workContext;
        }

        public ActionResult _MainLeftMenu()
        {
            var models = _cacher.GetMenuModels();
            return PartialView("../Partials/_MainLeftMenus", models);
        }

        public ActionResult Category(int categoryid)
        {
            
            var breadcrumbCacheKey = string.Format(PRODUCT_BREADCRUMB_MODEL_KEY, categoryid, _workContext.WorkingLanguage.Id);
            var category = dbContext.Categories.FirstOrDefault(p => p.Id == categoryid);

            var model = new CategoryViewModel
            {
                Id = categoryid,
                CategoryBreadcrumb = _cacheManager.Get(breadcrumbCacheKey, () =>
                {
                    var catBrs = new CategoryExtensions().GetCategoryBreadCrumb(category);
                    var breadcrumbModel = new List<CategoryViewModel>();
                    foreach (var catBr in catBrs)
                    {
                        breadcrumbModel.Add(new CategoryViewModel()
                        {
                            Id = catBr.Id,
                            Name = catBr.GetLocalized(x => x.Name),
                            SeName = catBr.GetSeName()
                        });
                    }
                    return breadcrumbModel;
                })
            };
            return View(model);
        }
	}
}